const _ = require('lodash');
const bcrypt = require('bcrypt');
const Rule = require('../../validate');


const prefix = '/api/user';
module.exports = app => {
    const {router, middleware} = app;

    //用户退出登录
    router.get(prefix + '/logout', middleware.api(), async ctx => {
        console.log('user logout', ctx.cookies);
        ctx.cookies.set('user', null);
        ctx.body = 'ok';
    });

    //用户列表
    router.get(prefix, middleware.api(), async ctx => {
        const User = ctx.app.model.User;

        const {page, limit, offset} = ctx.service.page.page();

        const whereUser = {id: {[ctx.app.Sequelize.Op.gt]: 1}};
        const whereLevel = {id: {[ctx.app.Sequelize.Op.gt]: 1}};

        if (!_.isEmpty(ctx.query.search)) {
            const like = {[ctx.app.Sequelize.Op.like]: '%' + ctx.query.search + '%'};
            const or = [{username: like}, {phone: like}, {email: like}];
            if (_.isInteger(parseInt(ctx.query.search))) {
                or.id = parseInt(ctx.query.search);
            }
            whereUser[ctx.app.Sequelize.Op.or] = or;
        }

        if (!_.isEmpty(ctx.query.level))
            whereLevel.id[ctx.app.Sequelize.Op.or] = ctx.query.level.split(',');


        let total = 2, list = [];

        await Promise.all([new Promise(resolve => {
            User.count({
                where: whereUser,
                include: [{model: ctx.app.model.UserLevel, as: 'level', where: whereLevel}]
            }).then(count => {
                total = count;
                resolve();
            });
        }), new Promise(resolve => {
            User.findAll({
                where: whereUser,
                limit,
                offset,
                order: [['id', 'desc']],
                attributes: ['id', 'username', 'phone', 'email', 'created_at'],
                include: [{model: ctx.app.model.UserLevel, as: 'level', where: whereLevel}]
            }).then(data => {
                list = data;
                resolve();
            });
        })]);

        ctx.body = {
            total,
            page,
            list,
        };
    });

    //指定用户
    router.get(prefix + '/:id', middleware.api(), async ctx => {
        ctx.body = await app.model.User.unscoped().findOne({raw: true, where: {id: ctx.params.id}});
        delete ctx.body.password;
    });

    //新建 或 编辑 用户
    router.post(prefix, middleware.api(2), async ctx => {
        const data = ctx.request.body;

        delete data.level;
        delete data.level_id;
        delete data.created_at;
        delete data.last_sign_in_at;


        let message;
        if (!(data.id > 0)) {//新建用户
            try {
                message = await ctx.service.user.register(data, true);
            } catch (e) {
                return ctx.helper.error(e.message);
            }
        } else {//编辑用户
            ctx.service.user.validateData(Rule.userEdit, data);

            if (data.id === ctx.user.id && data.disable)
                return ctx.helper.error('不能禁止自己登录');

            try {
                await ctx.service.user.checkUser(data)
            } catch (e) {
                return ctx.helper.error(e.message);
            }

            if (data.password && data.password.length >= 6) {
                data.password = await bcrypt.hash(data.password, 4);
            } else {
                delete data.password;
            }

            const user = await app.model.User.findByPk(data.id);
            if (!user)
                return ctx.helper.error('不能编辑不存在的用户');
            delete data.id;
            await user.update(data);

            message = '成功编辑账号信息';
        }

        ctx.body = message;
    });

    //删除用户
    router.delete(prefix + '/:id', middleware.api(2), async ctx => {
        ctx.body = '删除用户';
    });


};